<!--
  智慧社区管理系统 - 用户管理列表
  @author Wu.Liang
  @date 2024-01-01
  @updated 2024-12-21 - 按UI设计优化用户管理页面，完善权限控制
-->
<template>
    <div class="user-list">
        <!-- 页面标题和描述 -->
        <div class="page-header">
            <div class="page-title">
                <h1>用户管理</h1>
                <p class="page-desc">管理系统用户信息，包括居民、物业人员、管理员等</p>
            </div>
            <div class="page-actions">
                <PermissionGuard permission="user:create">
                    <el-button type="primary" :icon="Plus" @click="handleAdd">
                        新增用户
                    </el-button>
                </PermissionGuard>
                <PermissionGuard permission="user:export">
                    <el-button :icon="Download" @click="handleExport">
                        导出Excel
                    </el-button>
                </PermissionGuard>
            </div>
        </div>

        <!-- 搜索和筛选区域 -->
        <el-card class="search-card">
            <el-form :model="searchForm" :inline="true" class="search-form" label-width="80px">
                <el-form-item label="用户名">
                    <el-input 
                        v-model="searchForm.username" 
                        placeholder="请输入用户名" 
                        clearable 
                        style="width: 200px"
                        @keyup.enter="handleSearch"
                        :prefix-icon="User"
                    />
                </el-form-item>
                <el-form-item label="真实姓名">
                    <el-input 
                        v-model="searchForm.realName" 
                        placeholder="请输入真实姓名" 
                        clearable 
                        style="width: 200px"
                        @keyup.enter="handleSearch"
                        :prefix-icon="UserFilled"
                    />
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input 
                        v-model="searchForm.phone" 
                        placeholder="请输入手机号" 
                        clearable 
                        style="width: 200px"
                        @keyup.enter="handleSearch"
                        :prefix-icon="Phone"
                    />
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input 
                        v-model="searchForm.email" 
                        placeholder="请输入邮箱" 
                        clearable 
                        style="width: 200px"
                        @keyup.enter="handleSearch"
                        :prefix-icon="Message"
                    />
                </el-form-item>
                <el-form-item label="用户类型">
                    <el-select v-model="searchForm.userType" placeholder="请选择用户类型" clearable style="width: 150px">
                        <el-option label="居民" :value="1" />
                        <el-option label="物业" :value="2" />
                        <el-option label="管理员" :value="3" />
                        <el-option label="其他" :value="4" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
                        <el-option :label="STATUS.ENABLED" :value="1" />
<el-option :label="STATUS.DISABLED" :value="0" />
                        <el-option label="锁定" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="handleSearch">
                        搜索
                    </el-button>
                    <el-button :icon="Refresh" @click="handleReset">
                        重置
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 批量操作区域 -->
        <div class="batch-actions" v-if="multipleSelection?.length > 0">
            <el-alert 
                :title="`已选择 ${multipleSelection?.length} 项`" 
                type="info" 
                :closable="false"
                show-icon
            >
                <template #default>
                    <PermissionGuard permission="user:update">
                        <el-button type="primary" size="small" @click="handleBatchEnable">
                            批量启用
                        </el-button>
                    </PermissionGuard>
                    <PermissionGuard permission="user:update">
                        <el-button type="warning" size="small" @click="handleBatchDisable">
                            批量禁用
                        </el-button>
                    </PermissionGuard>
                    <PermissionGuard permission="user:delete">
                        <el-button type="danger" size="small" @click="handleBatchDelete">
                            批量删除
                        </el-button>
                    </PermissionGuard>
                    <el-button size="small" @click="clearSelection">
                        取消选择
                    </el-button>
                </template>
            </el-alert>
        </div>

        <!-- 表格区域 -->
        <el-card class="table-card">
            <el-table 
                ref="tableRef" 
                v-loading="loading" 
                :data="tableData" 
                stripe 
                border 
                style="width: 100%"
                @selection-change="handleSelectionChange"
                @sort-change="handleSortChange"
                :row-key="(row) => row.id"
            >
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column type="index" label="序号" width="60" align="center" :index="getIndex" />
                
                <!-- 用户基本信息 -->
                <el-table-column label="用户信息" min-width="200">
                    <template #default="{ row }">
                        <div class="user-info">
                            <el-avatar :src="row.avatar" :size="40">
                                {{ getUserInitial(row.realName || row.username) }}
                            </el-avatar>
                            <div class="user-details">
                                <div class="username">{{ row.username }}</div>
                                <div class="real-name">{{ row.realName || '-' }}</div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                
                <el-table-column prop="phone" label="手机号" width="130" />
                <el-table-column prop="email" label="邮箱" width="180" />
                
                <el-table-column label="用户类型" width="120" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getUserTypeTagType(row.userType)" size="small">
                            {{ row.userTypeText || getUserTypeText(row.userType) }}
                        </el-tag>
                    </template>
                </el-table-column>
                
                <el-table-column label="状态" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getStatusTagType(row.status)" size="small">
                            {{ getStatusText(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                
                <el-table-column prop="createTime" label="创建时间" width="160" sortable="custom">
                    <template #default="{ row }">
                        {{ formatDate(row.createTime) }}
                    </template>
                </el-table-column>
                
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <PermissionButton 
                            permission="user:view" 
                            type="primary" 
                            link 
                            :icon="View" 
                            @click="handleView(row)"
                        >
                            查看
                        </PermissionButton>
                        <PermissionButton 
                            permission="user:update" 
                            type="primary" 
                            link 
                            :icon="Edit" 
                            @click="handleEdit(row)"
                            :disabled="row.username === 'admin'"
                        >
                            编辑
                        </PermissionButton>
                        <PermissionButton 
                            permission="user:role:assign" 
                            type="primary" 
                            link 
                            @click="handleAssignRole(row)"
                        >
                            分配角色
                        </PermissionButton>

                        <el-dropdown @command="(command) => handleCommand(command, row)">
                            <el-button type="primary" link>
                                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                            </el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <PermissionButton 
                                        permission="user:update" 
                                        type="primary" 
                                        link 
                                        :disabled="row.username === 'admin'"
                                        @click="handleStatusToggle(row)"
                                    >
                                        {{ row.status === 1 ? '禁用' : '启用' }}
                                    </PermissionButton>
                                    <PermissionButton 
                                        permission="user:delete" 
                                        type="danger" 
                                        link 
                                        :disabled="row.username === 'admin'"
                                        @click="handleDelete(row)"
                                    >
                                        删除
                                    </PermissionButton>
                                    <PermissionButton 
                                        permission="user:password:reset" 
                                        type="warning" 
                                        link 
                                        @click="handleResetPassword(row)"
                                    >
                                        重置密码
                                    </PermissionButton>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-wrapper">
                <el-pagination
                    v-model:current-page="pagination.current"
                    v-model:page-size="pagination.size"
                    :page-sizes="[10, 16, 20, 50, 100]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </el-card>

        <!-- 用户表单对话框 -->
        <UserFormDialog 
            v-model="dialogVisible"
            :user-data="currentUser"
            :mode="dialogType"
            @success="handleSuccess"
        />

        <!-- 用户详情对话框 -->
        <UserDetailDialog 
            v-model="detailVisible"
            :user-data="currentUser"
        />

        <!-- 角色分配对话框 -->
        <RoleAssignDialog 
            v-model="roleAssignVisible"
            :user-id="currentUser?.id"
            @success="handleAssignRoleSuccess"
        />


    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { STATUS } from '@/constants/status'
import {
    Plus, Download, Search, Refresh, View, Edit, ArrowDown,
    User, UserFilled, Phone, Message
} from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { usePermissionStore } from '@/store/permission'
import { getUserList } from '@/api/user'
import PermissionButton from '@/components/permission/PermissionButton.vue'
import UserFormDialog from './components/UserFormDialog.vue'
import UserDetailDialog from './components/UserDetailDialog.vue'
import RoleAssignDialog from './components/RoleAssignDialog.vue'

import PermissionGuard from '@/components/PermissionGuard.vue'
import { showSuccess, showWarning } from '@/utils/message'
import { getTagType, getUserTypeTagType, getStatusTagType } from '@/utils/message'

// Store
const userStore = useUserStore()
const permissionStore = usePermissionStore()

// 响应式数据
const loading = ref(false)
const tableData = ref<any[]>([])
const total = ref(0)
const multipleSelection = ref<any[]>([])
const dialogVisible = ref(false)
const detailVisible = ref(false)
const currentUser = ref<any>(null)
const dialogType = ref('add')
const roleAssignVisible = ref(false)

// 搜索表单
const searchForm = reactive({
    username: '',
    realName: '',
    phone: '',
    email: '',
    userType: '',
    status: ''
})

// 分页
const pagination = reactive({
    current: 1,
    size: 16
})

// 方法
const loadData = async () => {
    loading.value = true
    try {
        const params = {
            current: pagination.current,
            size: pagination.size,
            username: searchForm.username || undefined,
            realName: searchForm.realName || undefined,
            phone: searchForm.phone || undefined,
            email: searchForm.email || undefined,
            userType: searchForm.userType ? Number(searchForm.userType) : undefined,
            status: searchForm.status ? Number(searchForm.status) : undefined
        }
        
        const response = await getUserList(params)
        tableData.value = response.data.records || []
        total.value = response.data.total || 0
    } catch (error: any) {
        console.error('加载用户列表失败:', error)
        ElMessage.error('加载数据失败')
    } finally {
        loading.value = false
    }
}

const handleSearch = () => {
    pagination.current = 1
    loadData()
}

const handleReset = () => {
    Object.keys(searchForm).forEach(key => {
        (searchForm as any)[key] = ''
    })
    pagination.current = 1
    loadData()
}

const handleSelectionChange = (selection: any[]) => {
    multipleSelection.value = selection
}

const handleSortChange = ({ prop, order }: { prop: string; order: string }) => {
    // 处理排序
    console.log('排序:', prop, order)
}

const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.current = 1
    loadData()
}

const handleCurrentChange = (current: number) => {
    pagination.current = current
    loadData()
}

const getIndex = (index: number) => {
    return (pagination.current - 1) * pagination.size + index + 1
}

const getUserInitial = (name: string) => {
    return name ? name.charAt(0).toUpperCase() : 'U'
}

const getUserTypeText = (type: number) => {
    const typeMap: Record<number, string> = {
        1: '居民',
        2: '物业',
        3: '管理员',
        4: '其他'
    }
    return typeMap[type] || '未知'
}

const getUserTypeTagType = (type: number) => {
    const typeMap: Record<number, string> = {
        1: 'info',
        2: 'success',
        3: 'danger',
        4: 'warning'
    }
    return typeMap[type] || 'info'
}

const getStatusText = (status: number) => {
    const statusMap: Record<number, string> = {
        0: '禁用',
        1: '启用',
        2: '锁定'
    }
    return statusMap[status] || '未知'
}

const getStatusTagType = (status: number) => {
    const statusMap: Record<number, string> = {
        0: 'warning',
        1: 'success',
        2: 'danger'
    }
    return statusMap[status] || 'info'
}

const formatDate = (date: string) => {
    if (!date) return ''
    return new Date(date).toLocaleString('zh-CN')
}

const handleAdd = () => {
    currentUser.value = null
    dialogType.value = 'add'
    dialogVisible.value = true
}

const handleEdit = (row: any) => {
    currentUser.value = { ...row }
    dialogType.value = 'edit'
    dialogVisible.value = true
}

const handleView = (row: any) => {
    currentUser.value = { ...row }
    detailVisible.value = true
}

const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除用户 "${row.username}" 吗？`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        // 模拟删除操作
        showSuccess('删除成功')
        loadData()
    } catch {
        // 用户取消
    }
}

const handleStatusToggle = async (row: any) => {
    const action = row.status === 1 ? '禁用' : '启用'
    try {
        await ElMessageBox.confirm(
            `确定要${action}用户 "${row.username}" 吗？`,
            `确认${action}`,
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        // 模拟状态切换
        row.status = row.status === 1 ? 0 : 1
        showSuccess(`${action}成功`)
    } catch {
        // 用户取消
    }
}

const handleResetPassword = async (row: any) => {
    try {
        await ElMessageBox.confirm(
            `确定要重置用户 "${row.username}" 的密码吗？`,
            '确认重置密码',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        // 模拟重置密码
        showSuccess('密码重置成功')
    } catch {
        // 用户取消
    }
}

const handleCommand = (command: string, row: any) => {
    switch (command) {
        case 'status':
            handleStatusToggle(row)
            break
        case 'delete':
            handleDelete(row)
            break
        case 'reset-password':
            handleResetPassword(row)
            break
    }
}

const handleBatchEnable = async () => {
    if (multipleSelection.value?.length === 0) {
        showWarning('请选择要操作的用户')
        return
    }
    
    try {
        await ElMessageBox.confirm(
            `确定要启用选中的 ${multipleSelection.value?.length} 个用户吗？`,
            '确认批量启用',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        // 模拟批量操作
        showSuccess('批量启用成功')
        loadData()
    } catch {
        // 用户取消
    }
}

const handleBatchDisable = async () => {
    if (multipleSelection.value?.length === 0) {
        showWarning('请选择要操作的用户')
        return
    }
    
    try {
        await ElMessageBox.confirm(
            `确定要禁用选中的 ${multipleSelection.value?.length} 个用户吗？`,
            '确认批量禁用',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        // 模拟批量操作
        showSuccess('批量禁用成功')
        loadData()
    } catch {
        // 用户取消
    }
}

const handleBatchDelete = async () => {
    if (multipleSelection.value?.length === 0) {
        showWarning('请选择要操作的用户')
        return
    }
    
    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${multipleSelection.value?.length} 个用户吗？此操作不可恢复！`,
            '确认批量删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        // 模拟批量操作
        showSuccess('批量删除成功')
        loadData()
    } catch {
        // 用户取消
    }
}

const clearSelection = () => {
    multipleSelection.value = []
}

const handleExport = () => {
    showSuccess('导出功能开发中...')
}

const handleSuccess = () => {
    dialogVisible.value = false
    loadData()
    showSuccess('操作成功')
}

const handleAssignRole = (row: any) => {
    currentUser.value = { ...row }
    roleAssignVisible.value = true
}

const handleAssignRoleSuccess = () => {
    roleAssignVisible.value = false
    loadData()
    showSuccess('角色分配成功')
}



// 生命周期
onMounted(() => {
    loadData()
})
</script>

<style scoped>
.user-list {
    padding: 0;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 16px;
}

.page-title h1 {
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
    color: var(--el-text-color-primary);
}

.page-desc {
    margin: 0;
    color: var(--el-text-color-regular);
    font-size: 14px;
}

.page-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.search-card {
    margin-bottom: 16px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
}

.search-form .el-form-item {
    margin-bottom: 0;
}

.batch-actions {
    margin-bottom: 16px;
}

.table-card {
    margin-bottom: 16px;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 12px;
}

.user-details {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.username {
    font-weight: 500;
    color: var(--el-text-color-primary);
}

.real-name {
    font-size: 12px;
    color: var(--el-text-color-regular);
}

.login-info {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.login-ip {
    font-size: 12px;
    color: var(--el-text-color-regular);
}

.pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: stretch;
    }
    
    .page-actions {
        justify-content: stretch;
    }
    
    .search-form {
        flex-direction: column;
    }
    
    .search-form .el-form-item {
        width: 100%;
    }
    
    .search-form .el-input,
    .search-form .el-select {
        width: 100% !important;
    }
}

@media (max-width: 480px) {
    .page-title h1 {
        font-size: 20px;
    }
    
    .user-info {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }
}
</style>
